import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
// import Layout from '@/views/layout'
// import Login from '@/views/login'
// import NotFound from '@/views/404'
// import Search from '@/views/search'
// import SearchResult from '@/views/search/result'
// import Article from '@/views/article'
// // 导入二级路由
// import Home from '@/views/layout/home'
// import QA from '@/views/layout/question'
// import Video from '@/views/layout/video'
// import User from '@/views/layout/user'
// import UserEdit from '@/views/layout/user/edit'
// import Chat from '@/views/layout/user/chat'

const Login = () => import('@/views/login')
const Layout = () => import('@/views/layout')
const NotFound = () => import('@/views/404')
const Home = () => import('@/views/layout/home')
const QA = () => import('@/views/layout/question')
const Video = () => import('@/views/layout/video')
const User = () => import(/* webpackChunkName: "user" */ '@/views/layout/user')
const Search = () => import(/* webpackChunkName: "search" */ '@/views/search')
const UserEdit = () =>
  import(/* webpackChunkName: "user" */ '@/views/layout/user/edit')
const SearchResult = () =>
  import(/* webpackChunkName: "search" */ '@/views/search/result')
const Article = () => import('@/views/article')
const Chat = () =>
  import(/* webpackChunkName: "user" */ '@/views/layout/user/chat')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home,
        meta: { isKeepAlive: true }
      },
      {
        path: '/question',
        component: QA
      },
      {
        path: '/video',
        component: Video
      },
      {
        path: '/user',
        component: User
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: SearchResult
  },
  {
    path: '/article',
    component: Article
  },
  {
    path: '/user/edit',
    component: UserEdit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '*',
    component: NotFound
  }
]

const router = new VueRouter({
  routes
})
// 需要拦截的页面(需要登录才可以访问到)
const loginURL = ['/user', '/user/edit', '/user/chat']

router.beforeEach(function (to, from, next) {
  // console.log('从哪来的form', from)
  // console.log('去哪里to', to)
  /*
  next() */
  // 1.
  const token = store.state.user.token.token
  // console.log(token)

  if (token) {
    next()
  } else {
    // 没有token
    if (loginURL.some((item) => to.path === item)) {
      // if成立，需要登录
      // next('/login') // 提示，导航跳转到/user 失败了，跳转到了/login
      // router.push('/login')
      // 带上回来的地址
      router.push({
        path: '/login',
        query: {
          back: to.fullPath
        }
      })
    } else {
      next()
    }
  }
})

export default router
